﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Linq;
using digitwhu.Models.IRepositorys;
using digitwhu.Models;

namespace digitwhu.Models.Repositorys
{
    public class UserRepository:Repository<UserInfo>,IUserRepository
    {
        public UserRepository(DataContext dbContext):base(dbContext)
        { 
        
        }

        #region 有用
        public  int AddUser(string userName, string password, string email)//用户注册
        {
            //用户注册，返回用户ID，密码用MD5单向加密
            //userName:用户名，即nickname，暂时可以相同
            //password:密码
            //email:注册邮箱，不可相同，登录凭邮箱验证
            //返回值：-1表示邮箱已经存在，-2表示注册失败(未能在表User中创建记录)，正数表示注册成功(返回的是用户的唯一编号)
     
            //查找邮箱是否存在，如果存在，返回-1；
            if (password == null || userName == null||email==null)//注册信息必须完整
            {
                return -2;//这个可以在前台控制
            }
            //查找邮箱是否存在
            var search = from u in context.GetTable<User>()
                         select u;
            foreach (var User in search)
            {
                if (User.emailAddress == email)
                {
                    return -1;//邮箱存在返回-1
                }
            }
            //对密码进行加密
            string md5Password = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(password, "MD5");
            //创建新用户
            User user = new User();
            user.nickName = userName;
            user.password = md5Password;
            user.emailAddress = email;
            user.lastLoginTime = DateTime.Now;
            context.GetTable<User>().InsertOnSubmit(user);
            context.SubmitChanges();
            //获得插入新用户数据库自动生成的用户编号
            var result = from c in context.GetTable<User>()
                         where c.emailAddress == email && c.nickName == userName
                         select c;
            int userId = -2;
            foreach(var User in result)
            {
                if (User.emailAddress == email)
                {
                    userId = User.id;
                    //注册成功还需要在表userInfo中创建一条记录
                    string sql = "INSERT INTO UserInfo(userId,registerDateTime) VALUES(" +
                        userId + ",'" +
                        DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "')";
                    context.ExecuteCommand(sql);//这条语句出现异常未处理
                    return userId;
                }
            }
            return -2;
        }
        public int GetUserLogin(string email, string password)//用户登录
        {
            //email:登录的邮箱地址
            //password:用户密码
            //返回值说明：正数表示登陆成功(返回用户ID),-1表示密码错误，-2表示用户名不存在
            if (password == null||email==null)  //这个应该在前台控制
            {
                return -1;
            }
            var search = from u in context.GetTable<User>()
                         select u;
            //对用户输入的密码进行加密处理
            string md5Password = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(password, "MD5");
            foreach (var User in search)
            {
                if (User.emailAddress == email)
                {
                    if (User.password == md5Password)
                    {
                        //登录成功，修改用户上次登录时间
                        User tmp = context.GetTable<User>().Single(c => c.id == User.id);
                        tmp.lastLoginTime = DateTime.Now;
                        context.SubmitChanges();
                        return User.id;
                    }
                    else {
                        return -1;//用户名存在，密码错误
                     }
                }
            }
            return -2;//用户名不存在
        }
     public bool UpdateUserInfo(int userId, string realName, decimal studentId, string school,
           DateTime birthday, string homeAddress, string avatar, int dormId, string nickName)//更新用户信息
        {
            //userId:用户编号
            //realName:真实姓名
            //studetnId:学号
            //school:学院
            //birthday:生日
            //homeAddress:家庭住址
            //avatar:头像
            //nickName:昵称
            //dormId:公寓Id(是在地图上面的building中公寓编号)
            //返回值：true:更新用户信息成功 false:更新用户信息失败
            string sqlDormId = "";
            if (dormId == -1)
            {
                //表示dormId为空不存在
            }
            else
            {
                sqlDormId = ",dormId=" + dormId;
            }
            string sqlStudentId = "";
            if (studentId == -1)
            {
                //表示studentId为空不存在
            }
            else
            {
                sqlStudentId = ",studentId=" + studentId;
            }
            string sqlBirthday = "";
            if (birthday.Equals(DateTime.Parse("1-1-1")))
            {
                //表示birthday为空不存在
            }
            else
            {
                sqlBirthday = ",birthday='" + birthday.ToString("yyyy-MM-dd HH:mm:ss") + "'";
            }
            string sql = "UPDATE UserInfo SET realName='" + realName +"'"+
                 sqlStudentId +
                ",school='" + school +"'"+
                 sqlBirthday +
               ",homeAddress='" + homeAddress +"'"+
               ",avatar='" + avatar + "'" +
                 sqlDormId +
               " WHERE userId=" + userId;
            //string sql2 = "UPDATE User SET nickName='" + nickName + "'" +
             //   "WHERE id=" + userId;
            User user = context.GetTable<User>().Single(u => u.id == userId);
            user.nickName = nickName;   //更改用户名
            try
            {
                //如果用户ID不存在，会发生异常的
                context.ExecuteCommand(sql);
                context.SubmitChanges();
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }
        public int UpdateUserPassword(string oldPassword, string newPassword,int userId)//用户更改密码
        {
            //oldPassword:登录的邮箱地址
            //newPassword:用户新密码
            //返回值：-1(用户Id非法)，-2原先密码错误，1表示操作成功
            //对用户输入的密码进行加密处理
            string oldpassword = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(oldPassword, "MD5");
            User user = context.GetTable<User>().Single<User>(u => u.id == userId);
            if (user == null)
            { 
                //用户ID非法
                return -1;
            }
            if (oldpassword.Equals(user.password))
            {
                //原先密码正确,则更改密码
                user.password = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(newPassword, "MD5");
                context.SubmitChanges();
                return 1;
            }
            else {
                return -2;  //原先密码错误
            }

        }
        public bool GetUserIsInUserAttention(int userPay, int userBe)//查询用户userPay是不是已经关注了用户userBe
        {
            //userPay:主动查询用户编号
            //userBe:被查询用户编号
            //返回值：true:用户userPay关注了用户userBe,false:true:用户userPay没有关注用户userBe
            var attention = from a in context.GetTable<Attention>()
                            where a.userPayAttention == userPay && a.userBeFocused == userBe
                            select a.userBeFocused;
            foreach (int i in attention)
            {
                //存在记录则返回正确
                return i == userBe; //二次验证
            }
            return false;
        }
        public bool GetUserInInUserBlackList(int userMake, int userBe)//查询用户userMake是不是已经拉黑了用户userBe
        {
            //userPay:主动查询用户编号
            //userBe:被查询用户编号
            //返回值：true:用户userMake已经拉黑了用户userBe,false:true:用户userMake没有拉黑用户userBe
            var attention = from a in context.GetTable<BlackList>()
                            where a.userMakeBlack == userMake && a.userBeBlack == userBe
                            select a.userBeBlack;
            foreach (int i in attention)
            {
                //存在记录则返回正确
                return i == userBe; //二次验证
            }
            return false;
        }
        #endregion
    }
}